﻿using System;
using System.Linq;
using Irony.Ast;
using Irony.Parsing;
using LibraryGuard.Interfaces;

namespace LibraryGuard.Internals.AST
{
	/// <summary>
	/// Represents string or pure text.
	/// </summary>
	internal class String
		: IValue
	{
		#region Fields
		private readonly string Value = string.Empty;
		#endregion

		#region Constructors
		public String(string val)
		{
			this.Value = val;
		}
		#endregion

		#region IValue Members
		/// <inheritdoc />
		public TypeCode GetBaseType(IDataProvider data)
		{
			return TypeCode.String;
		}

		/// <inheritdoc />
		public bool CanBeConvertedTo(TypeCode type, IDataProvider data)
		{
			switch(type)
			{
				case TypeCode.String:
					return true;
					
				case TypeCode.Boolean:
					return this.Value == "true" || this.Value == "false" || this.CanBeConvertedTo(TypeCode.Int32, data);

				case TypeCode.Int32:
					int tmp;
					return int.TryParse(this.Value, out tmp);
			}
			return false;
		}

		/// <inheritdoc />
		public object GetValue(TypeCode type, IDataProvider data)
		{
			switch (type)
			{
				case TypeCode.String:
					return this.Value;

				case TypeCode.Boolean:
					return System.Boolean.Parse(this.Value);

				case TypeCode.Int32:
					return int.Parse(this.Value);
			}
			return null;
		}
		#endregion

		#region Statics
		public static void Create(AstContext context, ParseTreeNode parseNode)
		{
			parseNode.AstNode = new String(parseNode.Token.ValueString);
		}
		#endregion
	}
}
